/*
 *
 * Copyright (C) 2012 Mauricio Garcia
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "msocket.h"

int Socket(int domain, int type, int protocol){
  int s = socket(domain,type,protocol);
  if ( s < 0 ){
    perror( "socket call failed" );
    exit( 1 );
  }
  return s;
}

void Bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen){
  if (bind(sockfd,addr,addrlen)<0){
    perror( "bind call failure" );
    exit( 1 );
  }
}

void Listen(int sockfd, int backlog){
  if (listen(sockfd,backlog)<0){
    perror( "listen call failed" );
    exit( 1 );
  }
}

int Accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen){
  int s = accept(sockfd,addr,addrlen);
  if (s<0){
    perror( "accept call failed" );
    exit( 1 );
  }
  return s;
}

int Recv(int sockfd,void* buf,size_t len,int flags){
 int rc = recv(sockfd,buf,len,flags);
  if (rc<0){
    perror( "\nrecv call failed" );
		if(errno != 104)
	    exit( 1 );
		else
			return -1;
  }
  return rc;
}

int Send(int sockfd, const void* buf,size_t len, int flags){
  int rc = send(sockfd,buf,len,flags);
  if (rc<0){
    perror( "send call failed" );
    exit( 1 );
  }
  return rc;
}

int Connect(int sockfd, const struct sockaddr* addr, socklen_t addrlen){
  int res = connect(sockfd,addr,addrlen);
  
  if (res<0){
    perror( "connect call failed" );
		if(errno == 111)
			return -1;
		else
	    exit( 1 );
  }
	return 1;
}

void Getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen){
 	if(getpeername(sockfd,addr,addrlen)<0){
    perror( "getpeername call failed" );
    exit( 1 );
	}
}
